import { loginAPI } from '@/api/login'

// 用户模块
const userModule = {
  namespaced: true,
  state () {
    return {
      token: window.localStorage.getItem('token'),
      refreshToken: window.localStorage.getItem('refreshToken')
    }
  },
  mutations: {
    setToken (state, tokenStr) {
      state.token = tokenStr
      window.localStorage.setItem('token', tokenStr)
    },
    setRefreshToken (state, refreshTokenStr) {
      state.refreshToken = refreshTokenStr
      window.localStorage.setItem('refreshToken', refreshTokenStr)
    }
  },
  actions: {
    // 登录的异步action
    async asyncLoginAction (store, formLoginObj) {
      // 1. 在这里发送登录请求
      const resp = await loginAPI(formLoginObj)
      const { token, refresh_token: refreshToken } = resp.data
      // 2. 把后台相应的 token 和 refreshToken 同步到 state 中
      store.commit('setToken', token)
      store.commit('setRefreshToken', refreshToken)
    }
  }
}

export default userModule
